package la.ge.kml;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;

import la.common.xml.Node2String;
import la.common.xml.XMLHelper;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class ErrorReportKMLBuilder {
	
	private XMLHelper xmlHelper;
	
	private XPathExpression xpathExpr;
	
	private Log logger = LogFactory.getLog(this.getClass());
	
	public ErrorReportKMLBuilder() {
		xmlHelper = new XMLHelper();
		XPath descXPath = xmlHelper.createXMLPath();
		descXPath.setNamespaceContext( KMLHelper.KML20XMLNSContext );
		try {
			xpathExpr = descXPath.compile( "/kml:kml/kml:Document/kml:Placemark/kml:description" );
		} catch (XPathExpressionException e) {
			throw new RuntimeException( e );
		}
	}

	public String build(String msg) { 
		try {
			Document doc = xmlHelper.sureLoadDocFromClassLoader( "/la/ge/kml/ErrorReportKMLBuilder.xml" );
			
			Element eDesc = (Element) xpathExpr.evaluate(
					doc, XPathConstants.NODE);
			
			eDesc.setTextContent( msg ); 
			
			return Node2String.node2String( doc );
			
		} catch (Exception e) {
			throw new RuntimeException( e );
		}
	}
	
	public String build(Throwable e) {
		logger.warn( "ErrorReportKMLBuilder:", e );
		return build( e.toString() );
	}
}
